package aooO.crm.Controller;



import aooO.crm.Service.UserService;
import aooO.crm.common.Utils.DateUtils;
import aooO.crm.common.Utils.UUIDUtils;
import aooO.crm.pojo.User;
import aooO.crm.pojo.returnObject;
import aooO.crm.pojo.stateCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Controller
public class UserController {
    @Autowired
    UserService userService;

    @RequestMapping("/settings/qx/user/toLogin.do")
    public String toLogin(){
        //请求转发到登录界面
        return "settings/qx/user/login";
    }

    /**
     * loginAct:loginAct,
     * 					loginPwd:loginPwd,
     * 					isRemPwd:isRemPwd
     * @return
     */
    @RequestMapping("/settings/qx/user/login.do")
    @ResponseBody
    public Object login(String loginAct, String loginPwd, String isRemPwd, HttpServletRequest request, HttpServletResponse response){
        //通过map将参数传给业务逻辑层
        Map<String,Object> map=new HashMap<>();
        map.put("loginAct",loginAct);
        map.put("loginPwd",loginPwd);    //只传查询数据库需要用到的数据
        User user = userService.selectUserByLoginActAndPwd(map);

        //返回信息封装在bean对象里面可以直接转化为json格式的字符串
        returnObject msg=new returnObject(stateCode.STATE_FAILURE,"",null);
        if (user==null){
            //没有找到对象
            msg.setMessage("用户名或密码错误");
        }else {
              String nowStr= DateUtils.FormatDateTime(new Date());   //当前时间
            if (nowStr.compareTo(user.getExpireTime())>0){
                //时间已过期
                msg.setMessage("用户已过期");
            }else if (stateCode.STATE_FAILURE.equals(user.getLockState())){
                //状态被锁定
                msg.setCode("状态被锁定");
            }else if (!user.getAllowIps().contains(request.getRemoteAddr())){
                //需要用request对象获得ip地址
                msg.setCode("ip地址受限");
            }else {
                //登陆成功
                msg.setCode(stateCode.STATE_SUCCESS);
                //由于user需要在各个页面中显示，因此存在session域中方面取出
                request.getSession().setAttribute(stateCode.SESSION_USER,user);
                //判断是否需要记住密码
                if (isRemPwd.equals("true")){
                    //存cookie
                    Cookie cookie1 = new Cookie("loginAct",loginAct);
                    cookie1.setMaxAge(10*24*60*60);
                    response.addCookie(cookie1);
                    Cookie cookie2 = new Cookie("loginPwd",loginPwd);
                    cookie2.setMaxAge(10*24*60*60);
                    response.addCookie(cookie2);
                }else {
                    //删除cookie
                    Cookie cookie1 = new Cookie("loginAct","1");
                    cookie1.setMaxAge(0);
                    response.addCookie(cookie1);
                    Cookie cookie2 = new Cookie("loginPwd","1");
                    cookie2.setMaxAge(0);
                    response.addCookie(cookie2);
                }
            }
        }
        return msg;
    }

    @RequestMapping("/settings/qx/user/logout.do")
    public String logout(HttpServletResponse response,HttpSession session){
        //删除cookie
        Cookie cookie1 = new Cookie("loginAct","1");
        cookie1.setMaxAge(0);
        response.addCookie(cookie1);
        Cookie cookie2 = new Cookie("loginPwd","1");
        cookie2.setMaxAge(0);
        response.addCookie(cookie2);

        //销毁session
        session.invalidate();

        //重定向到首页
        return "redirect:/";
    }


    @RequestMapping("workbench/saveEditPwd.do")
    @ResponseBody
    public Object updatePwd(String newPwd,HttpSession session){
        returnObject msg=new returnObject(stateCode.STATE_FAILURE,"");
        User user = (User) session.getAttribute(stateCode.SESSION_USER);
        Map<String,Object> map=new HashMap<>();
        map.put("id",user.getId());
        map.put("loginPwd",newPwd);
        try {
            int i = userService.updatePwd(map);
            if (i>0){
                msg.setCode(stateCode.STATE_SUCCESS);
            }else {
                msg.setMessage("修改失败，请重试！");
            }
        }catch (Exception e){
            e.printStackTrace();
            msg.setMessage("修改失败，请重试！");
        }

        return msg;
    }

//"settings/qx/user/toRegister.do"
    @RequestMapping("settings/qx/user/toRegister.do")
    public String toRegister(){
        return "/settings/qx/user/register";
    }

//    'settings/qx/user/register.do'
    @RequestMapping("settings/qx/user/register.do")
    @ResponseBody
    public Object register(User user,HttpServletRequest request){
        returnObject msg=new returnObject(stateCode.STATE_FAILURE,"");
        user.setId(UUIDUtils.uuid());
        user.setCreatetime(DateUtils.FormatDateTime(new Date()));
        user.setLockState(stateCode.STATE_SUCCESS);
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.YEAR,3);
        user.setExpireTime(DateUtils.FormatDateTime(calendar.getTime())); // 设置过期时间：两年后
        user.setAllowIps(request.getRemoteAddr()); // 默认当前本机登录ip
        try {
            int i = userService.insertUser(user);
            if (i>0){
                msg.setCode(stateCode.STATE_SUCCESS);
            }else {
                msg.setMessage("创建失败，请重试！");
            }
        }catch (Exception e){
            e.printStackTrace();
            msg.setMessage("创建失败，请重试！");
        }
        return msg;
    }
}
